package com.awei.study.dataStructure.queue;

import com.awei.study.dataStructure.link.LinkList_Abs;
import com.awei.study.dataStructure.queue.abs.Queue;

import java.util.Iterator;

/**
 * @Author liweilong
 * @Date 2023/5/23 12:28
 */
public class LinkQueue<E> extends LinkList_Abs implements Queue<E>, Iterable<E> {
    private static class LinkNode<E> {
        E value;
        LinkNode<E> next;

        public LinkNode(E value, LinkNode<E> next) {
            this.value = value;
            this.next=next;
        }
    }

    private LinkNode<E> head = new LinkNode<E>(null,null);
    private LinkNode<E> tail = head;
    private int size = 0;
    private int capacity = 10;

    {
        tail.next = head;
    }

    public LinkQueue() {
    }

    public LinkQueue(int capacity) {
        this.capacity = capacity;
    }

    @Override
    public boolean offer(E value) {
        if(isFull()) {
            return false;
        }
        LinkNode<E> newNode = new LinkNode<E>(value,head);
        tail.next = newNode;
        tail = newNode;
        size++;
        return true;
    }

    @Override
    public E poll() {
        if(isEmpty()) {
            return null;
        }
        LinkNode<E> p = head.next;
        head.next = p.next;
        if(p == tail) {
            tail = head;
        }
        size--;
        return p.value;
    }

    @Override
    public E peek() {
        if(isEmpty()) {
            return null;
        }
        LinkNode<E> p = head.next;
        return p.value;
    }

    @Override
    public boolean isFull() {
        return size == capacity;
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            LinkNode<E> p = head.next;
            @Override
            public boolean hasNext() {
                return p != head;
            }

            @Override
            public E next() {
                E value = p.value;
                p = p.next;
                return value;
            }
        };
    }
}
